package com.mrd.shiptask_shipowner.hwpush;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.sax.StartElementListener;
import android.util.Log;

import com.huawei.android.pushagent.api.PushEventReceiver;
import com.mrd.shiptask_shipowner.activity.ElectronManifestActivity;
import com.mrd.shiptask_shipowner.activity.MakeToOrderActivity;
import com.mrd.shiptask_shipowner.activity.NewsActivity;
import com.mrd.shiptask_shipowner.activity.NewsDetailActivity;
import com.mrd.shiptask_shipowner.constants.HttpConstant;
import com.mrd.shiptask_shipowner.serviecs.initdatadao.InitDatasDaoImpl;
import com.mrd.shiptask_shipowner.shiareutil.SharePreferenceUtil;
import com.mrd.shiptask_shipowner.unit_tools.FunctionOfActivity;
import com.mrd.shiptask_shipowner.unit_tools.HttpUrlConstant;
import com.mrd.shiptask_shipowner.unit_tools.HttpUtil;

/*
 * 接收Push所有消息的广播接收器
 */
public class MyReceiver extends PushEventReceiver {

	/*
	 * 显示Push消息
	 */
	public void showPushMessage(int type, String msg) {
		PustDemoActivity mPustTestActivity = MyApplication.instance()
				.getMainActivity();
		if (mPustTestActivity != null) {
			Handler handler = mPustTestActivity.getHandler();
			if (handler != null) {
				Message message = handler.obtainMessage();
				message.what = type;
				message.obj = msg;
				handler.sendMessageDelayed(message, 1L);
			}
		}
	}

	@Override
	public void onToken(Context context, String token, Bundle extras) {
		String belongId = extras.getString("belongId");
		String content = "现在获取token和belongId成功，token = " + token
				+ ",belongId = " + belongId;
		Log.d(PustDemoActivity.TAG, content);
		SharePreferenceUtil spu = new SharePreferenceUtil(context,
				HttpConstant.SAVE_USER);
		// 将获取到的token放入缓存，并比较最新得到的token是否有更改，有则存入最新的token，并发送到服务器
		try {
			if (token.length() > 0 && !token.equals(spu.getPushToken())) {
				spu.setPushToken(token);
				Map<String, Object> params9 = new HashMap<String, Object>();
				params9.put("ship", spu.getShip_id());
				params9.put("token", spu.getPushToken());
				params9.put("imei", FunctionOfActivity.getDeviceId(context));
				if (spu.getShip_id().length() > 0
						&& spu.getPushToken().length() > 0) {
					// 发送token等信息至服务器
					String result = HttpUtil
							.queryStringForPost(
									(HttpUrlConstant.SHIPBIZ_BASE_URL + HttpUrlConstant.SUBMIT_TOKEN_URL),
									params9, context).toString();
					JSONObject jo = new JSONObject(result);
					if (!(jo.has("result") && jo.getBoolean("result"))) {
						spu.setPushToken("");
					}
				}
			}
		} catch (Exception e) {
			spu.setPushToken("");
		}
		showPushMessage(PustDemoActivity.RECEIVE_TOKEN_MSG, content);
	}

	@Override
	public boolean onPushMsg(Context context, byte[] msg, Bundle bundle) {
		String content;
		try {
			content = "收到一条Push消息： " + new String(msg, "UTF-8");
			Log.d(PustDemoActivity.TAG, content);
			System.out.println("onPushMsg() action" + content);
			showPushMessage(PustDemoActivity.RECEIVE_PUSH_MSG, content);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public void onEvent(Context context, Event event, Bundle extras) {
		if (Event.NOTIFICATION_OPENED.equals(event)
				|| Event.NOTIFICATION_CLICK_BTN.equals(event)) {
			int notifyId = extras.getInt(BOUND_KEY.pushNotifyId, 0);
			if (0 != notifyId) {
				NotificationManager manager = (NotificationManager) context
						.getSystemService(Context.NOTIFICATION_SERVICE);
				manager.cancel(notifyId);
			}
			String content = "收到通知附加消息： "
					+ extras.getString(BOUND_KEY.pushMsgKey);
			System.out.println(content);
			String getPushKey = extras.getString(BOUND_KEY.pushMsgKey);
			try {
				// 判断是否已经登录，登录后才可以跳转到页面
				if ((new SharePreferenceUtil(context, HttpConstant.SAVE_USER)
						.getShip_name()).length() > 0) {
					JSONArray jObject = new JSONArray(getPushKey);
					String getPushValueOfKey = "";
					// 存在推送的电子舱单key则保存
					if (new JSONObject(jObject.get(0).toString()).has("eleId")) {
						getPushValueOfKey = new JSONObject(jObject.get(0)
								.toString()).getString("eleId");
						// InitDatasDaoImpl.getPushMessageAndReturnEleActivity(context,getPushValueOfKey);
						Intent intent = new Intent(context,
								ElectronManifestActivity.class);
						intent.putExtra("getPushValueOfKey", getPushValueOfKey);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(intent);
					}
					// 存在货运申请key则保存
					if (new JSONObject(jObject.get(0).toString()).has("apply")) {
						getPushValueOfKey = new JSONObject(jObject.get(0)
								.toString()).getString("apply");
						Intent intent = new Intent(context,
								MakeToOrderActivity.class);
						intent.putExtra("getPushValueOfKey", getPushValueOfKey);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(intent);
					}
					// 有消息推送过来，并存在message的参数，则为信息模块拦截处理
					if (new JSONObject(jObject.get(0).toString()).has("appMsg")) {
						getPushValueOfKey = new JSONObject(jObject.get(0)
								.toString()).getString("appMsg");
						Intent intent = new Intent(context,
								NewsDetailActivity.class);
						intent.putExtra("getPushValueOfKey", getPushValueOfKey);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(intent);
					}
				}
			} catch (Exception e) {
			}
			Log.d(PustDemoActivity.TAG, content);
			showPushMessage(PustDemoActivity.RECEIVE_NOTIFY_CLICK_MSG, content);
		} else if (Event.PLUGINRSP.equals(event)) {
			final int TYPE_LBS = 1;
			final int TYPE_TAG = 2;
			int reportType = extras.getInt(BOUND_KEY.PLUGINREPORTTYPE, -1);
			boolean isSuccess = extras.getBoolean(BOUND_KEY.PLUGINREPORTRESULT,
					false);
			String message = "";
			if (TYPE_LBS == reportType) {
				message = "LBS report result :";
			} else if (TYPE_TAG == reportType) {
				message = "TAG report result :";
			}
			Log.d(PustDemoActivity.TAG, message + isSuccess);
			showPushMessage(PustDemoActivity.RECEIVE_TAG_LBS_MSG, message
					+ isSuccess);
		}
		super.onEvent(context, event, extras);
	}

	@Override
	public IBinder peekService(Context myContext, Intent service) {
		return super.peekService(myContext, service);
	}
}
